/**
 * @ObjectPool.as
 * 
 * @author sodaChen mail:sujun10#21cn.com
 * @version 1.0
 * <br>Copyright (C), 2010 asFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:挂机冒险
 * <br>Date:2014-6-15
 */
package com.asframe.pool
{
	/**
	 * 基于工厂的生成对象的对象池
	 * @author sodaChen
	 * Date:2014-6-15
	 */
	public class FactoryObjectPool implements IObjectPool
	{
		protected var objectFactory:IPoolableObjectFactory;
		protected var maxIdle:int;
		protected var list:Array;
		public function FactoryObjectPool(objectFactory:IPoolableObjectFactory,maxIdle:int = 300)
		{
			this.objectFactory = objectFactory;
			this.maxIdle = maxIdle;
			list = [];
		}
		
		public function borrowObject(): *
		{
			var obj:* = null;
			if(list.length == 0)
			{
				obj = objectFactory.makeObject();
			}
			else
			{
				obj =  list.shift();
			}
			objectFactory.activateObject(obj);
			return obj;
		}
		
		public function returnObject(obj:* ):void
		{
			if(list.length < maxIdle)
			{
				objectFactory.passivateObject(obj);
				//放进池里
				list.push(obj);
			} 
			else
			{
				destroyObject(obj);
			}
		}
		
		public function getNumIdle():int
		{
			return list.length;
		}
		
		public function clear():void
		{
		}
		
		public function destroy(o:* =null):void
		{
		}
		
		public function isFull(obj:* ):Boolean
		{
			return false;
		}
		
		private function destroyObject(obj:* ):void
		{
			try
			{
				objectFactory.destroyObject(obj);
			}
			catch(error:Error)
			{
				trace("消耗对象失败" + error.getStackTrace());
			}
		}
	}
}